import React from "react";
import { HashRouter as Router, Switch, Route, Redirect, RouteChildrenProps } from "react-router-dom";

export interface IRouteProps {
    path: string;
    component: React.ComponentType<any>;
    children?: Array<IRouteProps>;  // 子路由
    redirect?: string;  // 重定向到的路由
    layout?: React.ComponentType<any>;  // 页面layout布局
    layoutProps?: any;
    auth?: boolean;  // 是否授权拦截
}

interface ICreateRoutesProps {
    routes: Array<IRouteProps>;
}

class CreateRoutes extends React.Component<ICreateRoutesProps> {
    createBasicRoute = (route: IRouteProps, index: number | string) => {
        const { path, component: Component, layout: Layout, auth } = route;
        if(auth){
            const isLogin = localStorage.getItem("token");
            if (!isLogin) {
                return (<Redirect to="/login" />);
              } else {
                return window.location.hash.includes("/login") ? (<Redirect to="/" />) : (<Route key={index} path={path} exact component={() => {
                  return Layout ? (<Layout {...route.layoutProps}><Component /></Layout>) : <Component />
                }}/>)
            }
        }
        return <Route exact key={index} path={path} component={() => {
            return Layout ? (<Layout {...route.layoutProps}><Component /></Layout>) : <Component />
        }} />
    }
    createFixRoute = (route: IRouteProps, index: number | string) => {
        const { path, component: RouteComponent, children  } = route;
        if(children){
            return <Route 
                key={index}
                path={path}
                children={(props: RouteChildrenProps) => {
                    let redirectPath = null;
                    return <RouteComponent {...props}>
                        <Switch>
                            {children.map((child, childIndex) => {
                                const { path: childPath, redirect } = child;
                                if(redirect){
                                    redirectPath = childPath;
                                }
                                return this.createFixRoute({...child, path: path + childPath}, `${index}-${childIndex}`);
                            })}
                            <Redirect from={path} to={`${path}${redirectPath || children[0].path}`} />
                        </Switch>
                    </RouteComponent>
                }}
            />
        }
        return this.createBasicRoute(route, index);
    }

    createRoute = () => {
        const { routes } = this.props;
        return (<Switch>
            {
                routes.map((route, index) => {
                    return this.createFixRoute(route, index);
                })
            }
            <Redirect from="/*" to="/" />
        </Switch>)
    }

    render(){ 
        return (<Router>
            {this.createRoute()}
        </Router>)
    }
}

export default CreateRoutes;